package edu.zjut.hjg.saas.web.controller.tenant;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_TENANT;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import edu.zjut.hjg.saas.biz.model.Tenant;
import edu.zjut.hjg.saas.biz.service.TenantService;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.web.model.TenantSession;

@Controller
@RequestMapping("/tenant/account")
public class AccountController {

    @Autowired
    private TenantService tenantService;

    @RequestMapping("/index.htm")
    @CookieSessionIn(value = SESSION_NAME_TENANT, param = "session")
    public void index(TenantSession session, Model model) {
        Tenant tenant = tenantService.findById(session.getId());
        model.addAttribute("balance", tenant.getBalance());
    }

    @RequestMapping(value = "/recharge.htm", method = RequestMethod.POST)
    @CookieSessionIn(value = SESSION_NAME_TENANT, param = "session")
    public String recharge(TenantSession session, @RequestParam("balance") double balance) {
        Tenant tenant = tenantService.findById(session.getId());
        tenant.setBalance(tenant.getBalance() + balance);
        tenantService.update(tenant);
        return "redirect:/tenant/account/index.htm";
    }
}
